package ua.kharkov.knure.pereverziev.diploma.web.command.ajax;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Flight;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Route;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;

public class GetEmptySits implements Command {

	private static final long serialVersionUID = -1004195229302087661L;
	private static final Logger log = Logger.getLogger(GetEmptySits.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		String result = "";

		final String routeId = request.getParameter("route");
		log.debug("routeId=" + routeId);

		final String direction = request.getParameter("direction");
		log.debug("Request parameter: direction --> " + direction);

		@SuppressWarnings("unchecked")
		final List<Route> directFlights = (List<Route>) request.getSession()
				.getAttribute("directFlights");
		@SuppressWarnings("unchecked")
		final List<Route> returnFlights = (List<Route>) request.getSession()
				.getAttribute("returnFlights");

		if (Integer.parseInt(direction) == GetPrice.FLIGHT_DIRECT) {
			final Route route = directFlights.get(Integer.parseInt(routeId));
			for (final Flight flight : route.getFlights()) {
				flight.getSchedule().getAirplane().getSitsQuantity();
				if ((flight.getSchedule().getAirplane().getSitsQuantity() - ServiceFactory
						.getInstance().getTicketService()
						.getEmptySitsQuantity(flight)) == 0)
					result = "No sits available";
			}
		} else {
			final Route route = returnFlights.get(Integer.parseInt(routeId));
			for (final Flight flight : route.getFlights()) {
				if ((flight.getSchedule().getAirplane().getSitsQuantity() - ServiceFactory
						.getInstance().getTicketService()
						.getEmptySitsQuantity(flight)) == 0)
					result = "No sits available";
			}
		}

		log.debug(result);
		return result;
	}
}
